package com.open4cn.simulator.core.connector.serialport;

import com.open4cn.simulator.core.exception.IllegalParameterException;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description
 * @Email yinxiaopeng@zj.tech
 * @date 2022-06-11 16:46
 */
public abstract class SerialPortInitializer {
    private SerialPortHandlerContext handlerContext;

    /**
     * 向pipeline传递数据
     *
     * @return
     */
    public void pipeline(byte[] msg) {
        getHandlerContext().reset();
        SerialPortHandler header = getHandlerContext().header();
        if (null == header) {
            throw new IllegalParameterException("未配置handler");
        }
        if (!(header instanceof SerialPortInboundHandler)) {
            throw new IllegalParameterException("handler类型错误");
        }
        SerialPortInboundHandler handler = (SerialPortInboundHandler) header;
        try {
            handler.serialPortRead(getHandlerContext(), msg);
        } catch (Exception e) {
            getHandlerContext().reset();
        }
    }


    /**
     * 向pipeline添加节点
     *
     * @param serialPortHandler
     */
    public void addLast(SerialPortHandler serialPortHandler) {
        if (null != serialPortHandler) {
            getHandlerContext().addLast(serialPortHandler);
        }
    }

    public void initSerialPort(SerialPortChannel serialPortChannel) {
        handlerContext = new SerialPortHandlerContext(serialPortChannel);
        initSerialPort();
    }

    private SerialPortHandlerContext getHandlerContext() {
        if (null == handlerContext) {
            throw new IllegalParameterException("SerialPortHandlerContext缺失");
        }
        return handlerContext;
    }

    protected abstract void initSerialPort();
}
